﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using AgileTimeTracker.Domain.Exceptions;

namespace AgileTimeTracker.Client.Wpf.Common
{
    public class RelayCommand : ICommand
    {
        private bool lastCanExecute = false;
        private Func<bool> canExecuteDelegate;
        private Action executeDelegate;

        public RelayCommand(Action executeDelegate, Func<bool> canExecuteDelegate = null)
        {
            this.executeDelegate = executeDelegate;
            this.canExecuteDelegate = canExecuteDelegate;
        }

        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            if (this.canExecuteDelegate == null)
            {
                return true;
            }

            var canExecute = this.canExecuteDelegate();
            if (this.lastCanExecute != canExecute)
            {
                this.lastCanExecute = canExecute;
                this.OnCanExecuteChanged();
            }

            return this.lastCanExecute;
        }

        public void Execute(object parameter)
        {
            try
            {
                this.executeDelegate();
            }
            catch(DomainValidationException validationException)
            {
                MessageBoxHelper.ShowAlert(validationException.Message);
            }
            catch(DomainException domainException)
            {
                MessageBoxHelper.ShowAlert(domainException.Message);
            }            
        }

        public void RaiseCanExecuteChanged()
        {
            this.CanExecute(null);
        }

        protected void OnCanExecuteChanged()
        {
            if (this.CanExecuteChanged != null)
            {
                this.CanExecuteChanged(this, EventArgs.Empty);
            }
        }
    }
}
